﻿using Tszy.Unlimited.Base.Infrastructure.Logging;

namespace Tszy.Unlimited.Base.BackgroundTasks;

/// <summary>
/// 后台任务接口。
/// </summary>
public interface IBackgroundProcessingService
{
    /// <summary>
    /// 间隔时间（单位：毫秒）。
    /// </summary>
    int DelayTime { get; }

    /// <summary>
    /// 工作任务。
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    Task DoWorkAsync(CancellationToken stoppingToken);
}

/// <summary>
/// 默认后台任务。
/// </summary>
public abstract class ScopedBackgroundServiceBase : IBackgroundProcessingService
{
    private string _name = string.Empty;

    /// <summary>
    /// 任务名称。
    /// </summary>
    protected string Name => string.IsNullOrWhiteSpace(_name) ? GetType().Name : _name;

    /// <summary>
    /// 间隔时间（单位：毫秒）。
    /// </summary>
    public virtual int DelayTime { get; set; } = 1000;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    public virtual async Task DoWorkAsync(CancellationToken stoppingToken)
    {
        try
        {
            await OnDoWorkAsync(stoppingToken);
        }
        catch (Exception exception)
        {
            TszyLogger.Instance.Fatal($"{Name} exception!", exception);
        }
    }

    /// <summary>
    /// 工作任务。
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    protected abstract Task OnDoWorkAsync(CancellationToken stoppingToken);
}